import threading
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from infomation import get_infomation
import random
import re

def is_id_card(id_card):
    # 18位身份证号的正则表达式，包含最后一位校验码
    pattern = r'^\d{17}[\dXx]$'
    return re.match(pattern, id_card) is not None


# 线程安全锁
lock = threading.Lock()

# 更新日志文件
def update_log_file(thread_id, data_chunk, infomation_person):
    log_path = f"日志/env{thread_id}.txt"

    with open(log_path, "r", encoding="utf-8") as f_re:
        lines = f_re.readlines()
        num = int(lines[2].strip("\n").split(":")[-1]) + 1

    lines[0] = f"总操作数:{len(data_chunk)}\n"
    lines[1] = f"当前处理身份证号:{infomation_person}\n"
    lines[2] = f"已完成数量:{str(num)}\n"

    with open(log_path, "w", encoding="utf-8") as f_wr:
        f_wr.writelines(lines)


# 定义处理数据的函数（供线程调用）
def process_data(data_chunk, thread_id):
    # 每个线程创建自己的 driver 实例
    driver = webdriver.Chrome()
    driver.get("https://tj.wuxianshixun.cn:8443/app/#/login")
    time.sleep(1)
    driver.maximize_window()
    time.sleep(1)

    # 登录操作
    driver.find_element(By.XPATH, '//*[@id="app"]/div/div[1]/div/form[1]/div[1]/input').send_keys("zjw")

    driver.find_element(By.XPATH, '//*[@id="app"]/div/div[1]/div/form[1]/div[2]/input').send_keys("zjw123")

    driver.find_element(By.XPATH, '//*[@id="app"]/div/div[1]/div/form[1]/input').click()


    for index, row in data_chunk.iterrows():
        # 获取当前是第几条数据
        with open(f"日志/env{thread_id}.txt", "r", encoding="utf-8") as f_re:
            num = int(f_re.readlines()[2].strip("\n").split(":")[-1])
            print(f"[线程{thread_id}] 目前执行数为{num},正在执行第{num + 1}个操作")
        if num >= len(data_chunk):
            print(f"{thread_id}数据读取完毕，请检查日志文件")
            break

        # 不同线程拿到不同的数据，函数要传递行数
        if thread_id == 1:
            name, infomation_person = get_infomation('东升6.23日门诊签约数据明细.xlsx', '门诊日志', num+2)
            print(f"第一个线程开始执行的索引为（包括表头的索引）:{2+num}")
            print()
        if thread_id == 2:
            name, infomation_person = get_infomation('东升6.23日门诊签约数据明细.xlsx', '门诊日志', num+230)
            print(f"第二个线程开始执行的索引为（包括表头的索引）:{230+num}")
            print()
        if thread_id == 3:
            name, infomation_person = get_infomation('东升6.23日门诊签约数据明细.xlsx', '门诊日志', num+458)
            print(f"第三个线程开始执行的索引为（包括表头的索引）:{458+num}")
            print()
        if thread_id == 4:
            name, infomation_person = get_infomation('东升6.23日门诊签约数据明细.xlsx', '门诊日志', num+686)
            print(f"第四个线程开始执行的索引为（包括表头的索引）:{686+num}")
            print()

        if not is_id_card(str(infomation_person)):
            with open(f"日志/env_cuowu.txt", "a", encoding="utf-8") as f_is_card:
                f_is_card.write(f"[线程{thread_id}],文件中索引为{(thread_id-1)*228+num+2},名字为：{name}， 当前处理的身份证号为：{infomation_person}\n")

            update_log_file(thread_id,data_chunk, infomation_person)
            print("%%%%%%%%%%%%%%%%%%%%%%%%%%5")

            continue

        # 页面二输入
        time.sleep(1)
        input_ids = driver.find_element(By.TAG_NAME, 'form')
        input_id1 = input_ids.find_element(By.XPATH, './div[1]/div[2]/div[1]/div[1]/input')
        input_id1.send_keys(infomation_person)
        time.sleep(2)

        input_id2 = input_ids.find_element(By.XPATH, './div[2]/div[2]/div[1]/div[1]/input')
        input_id2.clear()
        input_id2.send_keys(name)
        time.sleep(2)

        input_id3 = input_ids.find_element(By.XPATH, './div[3]/div[2]/div[1]/div[1]/input')
        input_id3.clear()
        input_id3.send_keys(name)
        time.sleep(2)

        time.sleep(1)
        driver.find_element(By.XPATH, '//*[@id="app"]/div/form/div[4]/div[2]/button[1]').click()

        # 页面跳转
        time.sleep(2)
        all_button = driver.find_element(By.CLASS_NAME, 'button-grid')
        buttons = all_button.find_elements(By.TAG_NAME, 'button')  # 获取所有button
        time.sleep(1)
        buttons[9].click()
        time.sleep(2)

        # 选择区域
        all_div_root = driver.find_element(By.TAG_NAME, 'form')
        divs = all_div_root.find_elements(By.XPATH, './div')
        time.sleep(1)

        # 清除所有已经选中的标签
        all_is_checkeds = all_div_root.find_elements(By.XPATH, '//label[@class="el-checkbox is-checked"]')
        for checked in all_is_checkeds:
            checked.click()
            time.sleep(1)
        # 清除第一个标题前内填入的文字
        divs[1].find_elements(By.TAG_NAME, 'label')[-1].click()
        element = divs[1].find_elements(By.TAG_NAME, 'input')[-1]
        element.clear()  # 先清除原有内容
        element.send_keys('腹部有异常')  # 再输入新内容

        # 点击并添加器官的病变标签
        type_gan = random.randint(2, 7)
        divs[2].find_elements(By.XPATH, './div[2]/div[1]/label')[-1].click()
        time.sleep(0.5)
        if type_gan in [2, 4]:
            kuaizhuang = f"大小为{round(random.random(), 2)}"
            divs[2].find_elements(By.TAG_NAME, 'label')[-type_gan].click()
            element = divs[2].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(kuaizhuang)  # 再输入新内容
        else:
            chengdu = ["轻度", "中度", "重度"]
            numbers = random.randint(0, 2)
            divs[2].find_elements(By.TAG_NAME, 'label')[-type_gan].click()
            element = divs[2].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(chengdu[int(numbers)])  # 再输入新内容

        type_dan = random.randint(2, 4)
        time.sleep(1)
        divs[3].find_elements(By.XPATH, './div[2]/div[1]/label')[-1].click()
        time.sleep(1)
        if type_dan in [3, 4]:
            kuaizhuang = f"大小为{round(random.random(), 2)}"
            divs[3].find_elements(By.TAG_NAME, 'label')[-type_dan].click()
            element = divs[3].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(kuaizhuang)  # 再输入新内容
        else:
            chengdu = ["轻度", "中度", "重度"]
            numbers = random.randint(0, 2)
            divs[3].find_elements(By.TAG_NAME, 'label')[-type_dan].click()
            element = divs[3].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(chengdu[int(numbers)])  # 再输入新内容

        type_yi = random.randint(2, 3)
        time.sleep(1)
        divs[4].find_elements(By.XPATH, './div[2]/div[1]/label')[1].click()
        time.sleep(1)
        divs[4].find_elements(By.TAG_NAME, 'label')[-type_yi].click()
        if type_yi in [2, 3]:
            chengdu = ["轻度", "中度", "重度"]
            numbers = random.randint(0, 2)
            element = divs[4].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(chengdu[int(numbers)])  # 再输入新内容

        type_pi = random.randint(2, 4)
        time.sleep(1)
        divs[5].find_elements(By.XPATH, './div[2]/div[1]/label')[-1].click()
        if type_pi in [4]:
            kuaizhuang = f"大小为{round(random.random(), 2)}"
            divs[5].find_elements(By.TAG_NAME, 'label')[-type_pi].click()
            element = divs[5].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(kuaizhuang)  # 再输入新内容
        else:
            chengdu = ["轻度", "中度", "重度"]
            numbers = random.randint(0, 2)
            divs[5].find_elements(By.TAG_NAME, 'label')[-type_pi].click()
            element = divs[5].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(chengdu[int(numbers)])  # 再输入新内容

        type_shen = random.randint(2, 7)
        time.sleep(0.5)
        divs[6].find_elements(By.XPATH, './div[2]/div[1]/label')[-1].click()
        if type_shen in [6, 7]:
            kuaizhuang = f"大小为{round(random.random(), 2)}"
            divs[6].find_elements(By.TAG_NAME, 'label')[-type_shen].click()
            element = divs[6].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(kuaizhuang)  # 再输入新内容
        else:
            chengdu = ["轻度", "中度", "重度"]
            numbers = random.randint(0, 2)
            divs[6].find_elements(By.TAG_NAME, 'label')[-type_shen].click()
            element = divs[6].find_elements(By.TAG_NAME, 'input')[-1]
            element.send_keys(chengdu[int(numbers)])  # 再输入新内容
        time.sleep(1)

        driver.find_element(By.XPATH, '//*[@id="app"]/div/form/div[10]/div[2]/button[1]').click()

        time.sleep(5)
        input_ids = driver.find_element(By.TAG_NAME, 'form')

        input_id2 = input_ids.find_element(By.XPATH, './div[2]/div[2]/div[1]/div[1]/input')
        input_id2.clear()
        input_id2.send_keys(name)
        time.sleep(2)

        input_id3 = input_ids.find_element(By.XPATH, './div[3]/div[2]/div[1]/div[1]/input')
        input_id3.clear()
        input_id3.send_keys(name)
        time.sleep(2)
        driver.find_element(By.XPATH, '//*[@id="app"]/div/form/div[4]/div[2]/button[2]').click()



        # 修改txt文件（显示执行到哪个文件了）
        with lock:
            update_log_file(thread_id, data_chunk, infomation_person)
        print(f'[线程{thread_id}] {name}提交成功')


    driver.quit()  # 关闭当前线程的浏览器


# 读取 Excel 数据
df_data = pd.read_excel("东升6.23日门诊签约数据明细.xlsx", sheet_name='门诊日志')

# 将数据分成四份
one_index = len(df_data) // 4
data_part1 = df_data.iloc[:one_index]
data_part2 = df_data.iloc[one_index:2*one_index]
data_part3 = df_data.iloc[2*one_index:3*one_index]
data_part4 = df_data.iloc[3*one_index:]

# 创建并启动四个线程
thread1 = threading.Thread(target=process_data, args=(data_part1, 1))
thread2 = threading.Thread(target=process_data, args=(data_part2, 2))
thread3 = threading.Thread(target=process_data, args=(data_part3, 3))
thread4 = threading.Thread(target=process_data, args=(data_part4, 4))

thread1.start()
thread2.start()
thread3.start()
thread4.start()

# 等待线程完成
thread1.join()
thread2.join()
thread3.join()
thread4.join()

print("所有线程已完成.")